<?php

namespace app\data\controller\control;
use app\data\model\ControlPlanListModel;
use app\data\model\ControlPlanModel;
use app\data\model\EnterStorehouseItemModel;
use app\data\model\EnterStorehouseModel;
use app\data\model\StorehouseModel;
use think\admin\Controller;
use think\facade\Db;

/**
 * 计划审核
 * Class Cate
 * @package app\data\controller\shop
 */
class PlanReview extends Controller
{
    /**
     * 指定数据表
     * @var string
     */
    protected $table = 'SnControlPlan';

    /**
     * 指定权限
     */
    protected $authorize = '';
    /**
     * 计划审核
     * @auth true
     * @menu true
     */
    public function index()
    {
        $this->title = '计划审核管理';

        $admin_user = session('user');
        $this->authorize = $admin_user['authorize'];
        $this->adminId = $admin_user['id'];
        $query = $this->_query($this->table)->equal('status,admin_id,plan_type,cate_id')->like('id,plan_title,admin_name');
        //权限重构
        $where[] = array( 'deleted','=', 0);
        $where[] = array( 'status','<>', -1);
        // $where[] = array( 'plan_status','>=', $admin_user['authorize']);
        if($this->authorize == 2){
            //主管
            $where[] = array('keshi_id','=',$admin_user['id']);
            $query->where($where)->order('id desc')->page();
        }else{
            $query->where($where)->order('id desc')->page();
        }
//        $query->where($where)->whereIn($whereIn)->order('id desc')->page();
    }


    /**
     * 列表数据处理
     * @param array $data
     */
    protected function _index_page_filter(array &$data)
    {
        foreach ($data as $k=>$v){
            $data[$k]['merge_time'] = Db::name('sn_control_plan_merge')->where('id',$v['merge_id'])->value('merge_time');
            $data[$k]['keshi_name'] = Db::name('system_user')->where('id',$v['keshi_id'])->value('username');
        }
        $this->storehouse_list = StorehouseModel::where('deleted',0)->select()->toArray();
        $this->userlist = Db::name('system_user')->where('authorize','1')->field('id,username,nickname')->select()->toArray();
    }

    /**
     * 查看流程
     * @auth true
     */
    public function ca_detail()
    {
        $this->title = '查看流程';
        $where = array(
            'collect_id'=>input('id')
        );
        $plan_list = Db::name('sn_control_plan_time')->where($where)->order('admin_authorize asc')->select();
        $this->assign('shlist',$plan_list);
        $plan_status = ControlPlanModel::where('id',input('id'))->find();
        $this->assign('info',$plan_status);
        $this->fetch();
    }
    /**
     * 表单结果处理
     * @param boolean $result
     */
    protected function _form_result($result)
    {
        if ($result && $this->request->isPost()) {
            $this->success('数据更新成功！');
        }
    }


    /**
     * 详情
     * @auth true
     */
    public function detail()
    {
        $this->title = '详情';
        $data = input('get.');
        $where = array(
            'deleted'=>0,
            'id'=>input('id')
        );
        $info = ControlPlanModel::where($where)->order('id desc')->find();
        $this->assign('info',$info);
        $plan_list = ControlPlanListModel::where('plan_id',$where['id'])->order('material_code asc')->select()->toArray();
        $total = 0;
        if($plan_list){
            foreach ($plan_list as $v){
                $total += $v['material_price'] * $v['material_num'];
            }
        }else{
            $plan_list = [];
        }
        $this->assign('plan_list',$plan_list);
        $this->assign('total',$total);
        $this->fetch();
    }


    /**
     * 审核拒绝
     * @auth true
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function refusal()
    {
        $adminUser = session('user');
        $plan_id = input('id');
        $refusal_cause = input('refusal_cause');
        $dateTime = date('Y-m-d H:i:s',time());
        $planTime = array('status'=>-1,'time'=>$dateTime,'to_reason'=>$refusal_cause);
        if($adminUser['id'] == 10000){
            $admin_id = Db::name('sn_control_plan_time')->where(['collect_id'=>$plan_id,'status'=>0])->order('admin_authorize asc')->value('admin_id');
            $planTime['to_reason'] = $refusal_cause.'(超级管理员操作)';
            $resut = Db::name('sn_control_plan_time')->where(['collect_id'=>$plan_id,'admin_id'=>$admin_id])->insertGetId($planTime);
        }else{
            $resut = Db::name('sn_control_plan_time')->where(['collect_id'=>$plan_id,'admin_id'=>$adminUser['id']])->insertGetId($planTime);
        }
        if (!is_int($resut)) {$this->error('服务器错误');}
        $this->_save($this->table, ['status' => '-1','plan_status'=>0,'reason_name'=>$adminUser['username'],'reason_id'=>$adminUser['id'],'to_reason'=>$refusal_cause,'reason_time'=>$dateTime]);
    }

    /**
     * 合并计划
     * @auth true
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function merge()
    {
        $data = input('post.');
        $idArr = explode(',',$data['id']);
        if(count($idArr) == 1){$this->error('请选择两个或两个以上合并');}
        $merge_list = ControlPlanModel::whereIn('id',$idArr)->select();
        foreach ($merge_list as $k=>$v){
            if($v['merge_id']){$this->error('编号：'.$v['id'].'的计划已被合并');}
        }
        $dateTime = date('Y-m-d H:i:s',time());
        $adminUser = session('user');
        $addAr = array(
            'title'=>date('Y年m月d日',time()).'合并计划',
            'plan_ids'=>$data['id'],
            'admin_id'=>$adminUser['id'],
            'admin_name'=>$adminUser['username'],
            'admin_nickname'=>$adminUser['nickname'],
            'plan_status'=>$adminUser['authorize'],
            // 'below_admin_id'=>$adminUser['id'],
            'merge_time'=>$dateTime
        );
        //开启事务
        Db::startTrans();
        try{
            $plan_apply_merge_id = Db::name('sn_control_plan_merge')->insertGetId($addAr);
            if(!$plan_apply_merge_id){$this->error('服务器错误，请重试~');}
            $planList = ControlPlanModel::whereIn('id',$idArr)->update(['merge_id'=>$plan_apply_merge_id]);
            if(!$planList){$this->error('服务器错误，请重试~');}
            $planList = ControlPlanListModel::whereIn('plan_id',$idArr)->update(['merge_id'=>$plan_apply_merge_id]);
            if(!$planList){$this->error('服务器错误，请重试~');}
            // 执行提交操作
            Db::commit();
        }catch(\Exception $e){
            // 回滚事务
            Db::rollback();
            // 获取提示信息
            $this->error($e->getMessage());
        }
        $this->success('数据合并成功');
    }


    /**
     * 确认入库
     * @auth true
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function warehousing()
    {
        $plan_id = input('id');
        $controlInfo = ControlPlanModel::where('id',$plan_id)->with('plan_list')->find()->toArray();
        $admin_user = session('user');
        $enter['title'] = $controlInfo['plan_title'];
        $enter['admin_id'] = $controlInfo['admin_id'];
        $enter['admin_name'] = $controlInfo['admin_name'];
        $enter['operate_id'] = $admin_user['id'];
        $enter['operate_name'] = $admin_user['username'];
//        $enter['status'] = 1;
        $enter['storehouse_id'] = input('storehouse_id');
        $enter['plan_id'] = $plan_id;
        //开启事务
        Db::startTrans();
        try{
            $enter_id = EnterStorehouseModel::insertGetId($enter);
            if(!$enter_id) {throw new \Exception("服务器错误");}
            $cate_list = array();
            foreach ($controlInfo['plan_list'] as $k=>$v){
                $cate_list[] = array(
                    'material_code'=>$v['material_code'],
                    'material_name'=>$v['material_name'],
                    'material_model'=>$v['material_model'],
                    'material_unit'=>$v['material_unit'],
                    'material_price'=>$v['material_price'],
                    'material_num'=>$v['material_num'],
                    'material_xjprice'=>$v['material_xjprice'],
                    'enter_id'=>$enter_id,
                    'cate_id'=>$v['cate_id'],
                    'admin_id'=>$controlInfo['admin_id'],
                    'admin_name'=>$controlInfo['admin_name'],
                    'storehouse_id'=>input('storehouse_id'),
                    'create_at'=>date('Y-m-d H:i:s',time())
                );
            }
            //添加子表数据
            $res = EnterStorehouseItemModel::insertAll($cate_list);
            if(!$res) {throw new \Exception("服务器错误");}
            //修改计划状态
            $controRes = ControlPlanModel::where('id',$plan_id)->update(['enter_storehouse_status'=>1]);
            if(!$controRes) {throw new \Exception("服务器错误");}
            Db::commit();
        }catch(\Exception $e){
            // 回滚事务
            Db::rollback();
                // 获取提示信息
            $this->error($e->getMessage());die;
        }
        $this->success('入库成功！');
    }
    
    
    
    /**
     * 日志列表
     * @auth true
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function detail_log()
    {
        $this->title = '日志列表';
        $data = input('get.');
        $where = array('key'=>$data['id']);
        $info = Db::name('sn_control_plan_log')->where($where)->order('id desc')->select();
        $this->assign('plan_list',$info);
        $this->fetch();
    }

    /*
    * 数量/备注  日志添加
    */
    public function remarks(){
        $index = input('index');
        $id = input('id');
        $remarks = input('remarks');
        $number = input('numbers');
        $info = ControlPlanListModel::where('id',$index)->find();
        if($number>=0 && $number != '' && $number < $info['material_num']){
            if($info['material_num'] < $number){return json(['code'=>400,'msg'=>'数量过大']);}
            //开启事务
            Db::startTrans();
            try{
                $saveAll = array(
                    'material_num'=>$number,
                    'material_xjprice'=>round($number * $info['material_price'],2),
                );
                $saveinfo = ControlPlanListModel::where('id',$index)->update($saveAll);
                if($saveinfo === false){return json(['code'=>500,'msg'=>'服务器繁忙']);}
                $admin_user = session('user');
                //添加日志
                $insetAll = array(
                    'plan_id'=>$id,
                    'remarks'=>$remarks,
                    'key'=>$index,
                    'original_num'=>$info['material_num'],
                    'save_num'=>empty($number)?$info['material_num']:$number,
                    'admin_id'=>$admin_user['id'],
                    'admin_name'=>$admin_user['username'],
                    'time'=>date('Y-m-d H:i:s',time())
                );
                $logId = Db::name('sn_control_plan_log')->insertGetId($insetAll);
                if(!$logId){return json(['code'=>500,'msg'=>'服务器繁忙']);}
                Db::commit();
            }catch(\Exception $e){
                // 回滚事务
                Db::rollback();
                // 获取提示信息
                $this->error($e->getMessage());die;
            }
            return json(['code'=>200,'msg'=>'数据已更新']);
        }else{
            return json(['code'=>400,'msg'=>'数量未修改']);
        }
    }

}